package com.edu.juc.completableFuture.example;

import com.edu.juc.completableFuture.example.bean.NetMall;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class CompletableFutureMallTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        List<NetMall> list = Arrays.asList(
                new NetMall("jd"),
                new NetMall("taobao"),
                new NetMall("tmall"),
                new NetMall("amazon")
        );
        ConcurrentHashMap<String, BigDecimal> map = new ConcurrentHashMap<>();
        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        ExecutorService executor = Executors.newFixedThreadPool(list.size());
        list.forEach(mall -> CompletableFuture.supplyAsync(() ->
                        mall.getPrice("apple"), executor)
                .whenComplete((v, e) -> {
                    if (e == null) {
                        map.put(mall.getMallName(), v);
                        countDownLatch.countDown();
                        System.out.println(mall.getMallName() + "计算结束...");
                    }
                }).exceptionally(e -> {
                    e.printStackTrace();
                    return null;
                }));

        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("等待计算结果中.....");
                countDownLatch.await();
                System.out.println("----计算结果：" + map);
                long end = System.currentTimeMillis();
                System.out.println("----耗时：" + (end - start));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);

        executor.shutdown();

    }
}
